package com.aircms.common;


import com.aircms.util.JwtUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

public class Common {

    /**
     * 获取ip
     * @return
     */
    public static String getIp() {
        HttpServletRequest request=request();
        String remoteAddr = "";
        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }
        return remoteAddr;
    }


    /**
     * 获取客户端浏览器版本信息
     * @return
     */
    public static String getUserAgent(){
        HttpServletRequest request=request();
        return request.getHeader("User-Agent");
    }

    /**
     * 获取头部token信息
     * @return
     */
    public static  String getAuthorization(){
        HttpServletRequest request=request();
        return request.getHeader("Authorization");
    }

    /**
     * 获取登录用户id
     * @return
     */
    public static int getUserId(){
        return Integer.parseInt(JwtUtil.parserJwt(getAuthorization(),"id"));
    }

    /**
     * 获取登录用户名称
     * @return
     */
    public static String getUserName(){
        return JwtUtil.parserJwt(getAuthorization(),"name");
    }



    /**
     * 获取登录用户的角色id
     * @return
     */
    public static String getUserRoleId(){
        String string=JwtUtil.parserJwt(getAuthorization(),"role_ids");
        return JwtUtil.parserJwt(getAuthorization(),"role_ids");
    }

    /**
     *
     * @return
     */
    private static HttpServletRequest request(){
        ServletRequestAttributes requestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request= requestAttributes.getRequest();
        return request;
    }


    /**
     * 判断是否为整数
     * @param str 传入的字符串
     * @return 是整数返回true,否则返回false
     */

    public static boolean isInteger(String str) {
        if(str.isEmpty()){
            return false;
        }
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }





}
